package com.neuedu.sprinttx.service;


import com.neuedu.sprinttx.dao.AccountDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class AccountService {

    @Resource
    AccountDao accountDao;


    /**
     * 转账的功能
     * @return
     */
    @Transactional(value="txManager",propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,rollbackFor = Exception.class )
    public boolean transfer(boolean flag) throws Exception {
         //开启事务 ，不要自动提交

        //给张三的账户 - 1000
        String sql = "UPDATE account SET amount = amount - 1000 WHERE id = ?";
        Object[] args = {1};

        int count = accountDao.update(sql,args);

        System.out.println("count = " + count);


        /***
         * 中间业务 业务逻辑
         */
        if(flag){
            throw new Exception("业务操作失败了");
        }
        

        //给李四的账户 + 1000
        String sql2 = "UPDATE account SET amount = amount + 1000 WHERE id = ?";
        Object[] args2 = {2};

        int count2 = accountDao.update(sql2,args2);

        System.out.println("count2 = " + count2);


        //commit

        //报错回滚

        return count + count2 ==2 ;

    }


}
